package com.xxkj.drugtraceability.ui.drugscan

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.GsonBuilder
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.bean.BoxCodeRequest
import com.xxkj.drugtraceability.net.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: zhoujingjin
 * created on: 2024/9/10 18:57
 * description:
 */
class DrugScanViewModel(application: Application,private val drugScanRepository: DrugScanRepository):BaseViewModel(application) {
    var dataList = MutableLiveData<MutableList<String>>()
    var data = mutableListOf<String>()
    var uiState = MutableLiveData<UiState<Boolean>>()
    var hasData = false
    var isShowMsfxRadio = MutableLiveData<Boolean>()
    fun clearData(){
        dataList.postValue(mutableListOf())
        data.clear()
    }
    fun drugInStorage(data:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                uiState.postValue(UiState(isLoading = true))
                    val result = drugScanRepository.drugInStorage(data)
                if (result is Result.Success){
                    uiState.postValue(UiState(isLoading = false,isSuccess = true))
                }else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }
            }
        }
    }

    /**
     * 扫码放心码
     */
    fun queryTracCodeByBoxCode(barcode:String){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val result = drugScanRepository.queryTracCodeByBoxCode(GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(BoxCodeRequest(barcode,"1")));
                if (result is Result.Success){
                    data.addAll(result.data.data)
                    dataList.postValue(data)
                }else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }
            }
        }
    }
    /**
     * 是否对接扫码放心码
     */
    fun isOpenMsfx(){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val result = drugScanRepository.isOpenMsfx()
                if (result is Result.Success){
                    if (result.data.data)
                        isShowMsfxRadio.postValue(true)
                }/*else if (result is Result.Error){
                    uiState.postValue(UiState(isLoading = false,isError = result.errorData?:result.exception.message))
                }*/
            }
        }
    }
}